<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('FeedbackEmail')) return;
/**
 * Feedback plugin
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage feedback
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/AlohaCart
 */

/**
 *  Class that helps to work with email
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com) 
 */
class FeedbackEmail {
    private $formName;
    private $config;
    
    /**
     *  Email send method. Can be 'PHPMailer' or 'mail'
     */ 
    private $send_method = 'PHPMailer';
    
    public function __construct($form_name, $config){
        $this->formName = $form_name;
        $this->config = $config;
        
        if (isset($config['send_method']))
        $this->SetSendMethod($config['send_method']);
              
        // Include configs
        //include_spip('formulaires/'.$this->formName.'/config');
    }
    
    public function SetSendMethod($method) {
        if (in_array($method, array('PHPMailer', 'mail')))
            $this->send_method = $method;
    }
    
    /**
     *  Explode emails separated with comma
     */
    public function explodeEmails($emails) {
        // Remove whitespaces
        $emails = str_replace(' ', '', $emails);
        // Explode emails, separated by comma    
        $emails = explode(',',$emails); 
        
        return $emails;
    }
    
    /**
     *  Send Admin and User messages.
     *  NB: user email must be in "email" post field!
     */
    function sendMessages() {
        $result = true;
        $result = $this->sendAdminMessage();
        if ($this->config['send_user'])
            $result = $this->sendUserMessage(_request('email'));
        // TODO: Удалить файлы после прикрепления к письмам, если не нужно отправлять ссылки на них
        return $result;    
    }
    
    function sendAdminMessage() {
        $config = $this->config;
        $emails = $this->explodeEmails($config['admin_email']);
        $flag_result = false;
        foreach ($emails as $email) {
            $email_to = $email;
            $subject = extraire_multi($config['admin_subject'], $GLOBALS['meta']['langue_site']);
            $message = recuperer_fond('formulaires/'.$config['form_name'].'/admin_template', array_merge($_REQUEST, array('config'=>$config, 
                'uploaded_files_data'=>$GLOBALS['uploaded_files_data_'.$this->formName])));
            if (isset($config['user_data_from']) && $config['user_data_from']) {
                $from_name = _request('name');
                $from_email = _request('email');
            } else {
                // Admin will receive message in site's main language
	            $from_name = extraire_multi($config['from_name'], $GLOBALS['meta']['langue_site']);
        	    $from_email = $config['from_email'];
            }
            
            $attach_files = isset($this->config['attach_files']['allow_attach']) && $this->config['attach_files']['allow_attach'];
            
            if ($this->send_method == 'PHPMailer')
                $flag_result = $this->sendMessageViaPHPMailer($email_to, $subject, $message, $from_name, $from_email, $attach_files, $this->config['attach_files_for_admin']);
            else if ($this->send_method == 'mail')
                $flag_result = $this->sendMessageViaMail($email_to, $subject, $message, $from_name, $from_email);
        }
        
        return $flag_result;        
    }
    
    function sendUserMessage($user_email = false) {
        if (!$user_email) $user_email = _request('email');        
        if (!$user_email) return false;
        
        $config = $this->config;
            
        $subject = extraire_multi($config['user_subject']);
        $message = recuperer_fond('formulaires/'.$config['form_name'].'/user_template', array_merge($_REQUEST, array('config'=>$config,
            'uploaded_files_data'=>$GLOBALS['uploaded_files_data_'.$this->formName])));
        $from_name = extraire_multi($config['from_name']);
        $from_email = $config['from_email'];
        
        $attach_files = isset($this->config['attach_files']['send_user']) && $this->config['attach_files']['send_user'] && isset($this->config['attach_files']['allow_attach']) && $this->config['attach_files']['allow_attach']; 
        
            
        if ($this->send_method == 'PHPMailer')
            return $this->sendMessageViaPHPMailer($user_email, $subject, $message, $from_name, $from_email, $attach_files, $this->config['attach_files_for_user']);
        else if ($this->send_method == 'mail')
            return $flag_result = $this->sendMessageViaMail($user_email, $subject, $message, $from_name, $from_email);
        
        return false;    
    }
    
    private function sendMessageViaPHPMailer($email_to, $subject, $message, $from_name, $from_email, $attach_files=false, $additional_files_to_attach=array()) {
        $mail = new PHPMailer();
        $mail->CharSet = 'utf8';
        $mail->Subject = "=?UTF-8?B?" . base64_encode($subject)."?=";
        $mail->SetFrom($from_email, "=?UTF-8?B?" . base64_encode($from_name)."?=");
        $mail->AddAddress($email_to);
        $mail->IsHTML(true);
        $mail->Body = $message;
        
        if ($attach_files) {
            $files_data = $GLOBALS['uploaded_files_data_'.$this->config['form_name']]; 
            if (isset($files_data) && is_array($files_data) && !empty($files_data)) {
                foreach ($files_data as $file_data) {
                    $mail->AddAttachment($file_data['full_path']);                    
                }
            }    
        }
        
        if (isset($additional_files_to_attach) && is_array($additional_files_to_attach) && !empty($additional_files_to_attach)) {
            foreach ($additional_files_to_attach as $file) {
                if (file_exists($file))
                    $mail->AddAttachment($file);
            }
        }
        
    
        return (bool)$mail->Send();
    }
    
    private function sendMessageViaMail($email_to, $subject, $message, $from_name, $from_email) {
        $subject = "=?UTF-8?B?" . base64_encode($subject)."?=";
        
        $email_to = $email_to;
        
        $header = 'MIME-Version: 1.0' . "\n" . 'Content-type: text/html; charset=UTF-8';
        //$email_from = 'no-reply@'.$_SERVER['SERVER_NAME'];
        $name_from = "=?UTF-8?B?" . base64_encode($from_name)."?="; 
        $header = $header."\n".'From: '.$name_from.' <'.$from_email.'> ';
            
        return mail($email_to, $subject, $message, $header);
    }
} 
?>